<template>
  <div class="main-box">
    <el-button
      type="primary"
      style="margin-bottom: 16px"
      icon="el-icon-plus"
      @click="open"
    >
      新增会员
    </el-button>
    <BaseTable :request="request" ref="baseTable">
      <el-table-column prop="id" label="ID" width="120px" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column label="头像">
        <template slot-scope="scope">
          <el-avatar
            v-if="scope.row.avatar"
            shape="square"
            size="medium"
            :src="scope.row.avatar"
          />
        </template>
      </el-table-column>
      <el-table-column prop="user_group" label="用户组">
        <template slot-scope="scope">
          <span v-if="scope.row.userGroup">
            {{ scope.row.userGroup.title }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="max_score" label="等级">
        <template slot-scope="scope">
          <span v-if="scope.row.userGrade">
            {{ scope.row.userGrade.title }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="nickname" label="昵称" />
      <el-table-column prop="status" :label="$t('状态')">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == 1" size="small" type="success">
            已启用
          </el-tag>
          <el-tag v-else-if="scope.row.status == 2" size="small" type="info">
            已禁用
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="mobile" label="手机" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="last_login_time" label="最后登录时间" />
      <el-table-column prop="create_time" :label="$t('创建时间')" />
      <el-table-column prop="update_time" label="修改时间" />
      <el-table-column
        :label="$t('操作')"
        width="100px"
        fixed="right"
        align="right"
      >
        <template slot-scope="scope">
          <EditBtn @click="editUser(scope.row)" />
          <EnableBtn
            v-if="scope.row.status == 3"
            @click="editUserStatus(scope.row, 1)"
          />
          <DisableBtn v-else @click="editUserStatus(scope.row, 3)" />
        </template>
      </el-table-column>
    </BaseTable>
    <BaseDialog
      :title="adminForm.id ? '编辑会员' : '添加会员'"
      :dialog-show.sync="dialogAdmin"
      width="60"
      footer
      @submit="submit"
    >
      <el-form
        ref="adminForm"
        class="user-form-container"
        :model="adminForm"
        :rules="adminRules"
        label-position="top"
      >
        <el-col :span="12">
          <el-form-item label="用户名：" prop="username">
            <el-input v-model="adminForm.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="密码：" prop="password">
            <el-input
              v-model="adminForm.password"
              placeholder="请输入密码，不填默认为123123"
            />
          </el-form-item>

          <el-form-item label="会员分组：" prop="user_group">
            <el-select
              v-model="adminForm.user_group"
              placeholder="请选择会员分组"
            >
              <el-option
                v-for="item in groupList"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="头像：" prop="avatar">
            <div class="attachment_imgBox" @click="openList('icon')">
              <img
                v-if="adminForm.avatar"
                :src="iconUrl"
                class="attachmentImg"
              />
              <i v-else class="el-icon-camera" />
            </div>
            <Attachment
              ref="attachment"
              :dialog-show.sync="dialogShow"
              :attachment-type="attachmentType"
              @func="getData"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="性别：" prop="sex">
            <el-radio v-model="adminForm.sex" :label="0">保密</el-radio>
            <el-radio v-model="adminForm.sex" :label="1">男</el-radio>
            <el-radio v-model="adminForm.sex" :label="2">女</el-radio>
          </el-form-item>
          <el-form-item label="昵称：" prop="nickname">
            <el-input v-model="adminForm.nickname" placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="手机号：" prop="mobile">
            <el-input v-model="adminForm.mobile" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="邮箱：" prop="email">
            <el-input v-model="adminForm.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="生日：" prop="birthday">
            <el-date-picker
              v-model="adminForm.birthday"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-col>
      </el-form>
    </BaseDialog>
  </div>
</template>
<script>
import userApi from '@/api/users.js'
export default {
  data() {
    return {
      request: userApi.userList,
      groupList: [],
      attachmentLimit: 10,
      dialogShow: false,
      attachmentData: [],
      attachmentType: '',
      iconUrl: '',
      tableData: [],
      searchForm: {},
      dialogAdmin: false,
      options: [], // 角色
      name: '', // 暂存会员姓名
      adminForm: {
        username: '',
        password: '',
        avatar: '',
        user_group: '',
        sex: 0,
        nickname: '',
        mobile: '',
        email: '',
        birthday: '',
        id: ''
      }, // 新增会员表单
      adminRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        user_group: [
          { required: true, message: '请选择用户分组', trigger: 'change' }
        ]
      }
    }
  },
  created() {},
  updated() {},
  methods: {
    getData(data) {
      if (data.length > 1) {
        this.$message.error(this.$t('最多只能选择一张图片'))
      } else {
        if (this.uploadType == 'icon') {
          this.adminForm.avatar = data[0].url
          this.iconUrl = data[0].url
        }
        this.dialogShow = false
      }
    },
    // 打开附件弹窗
    openList(val) {
      this.dialogShow = true
      this.attachmentType = 2
      this.$nextTick(() => {
        this.$refs.attachment.getAttachmentList()
        this.$refs.attachment.$refs.AttachmentCate.getCateList(0)
        console.log(this.$refs.attachment.$refs.AttachmentCate)
      })
      this.uploadType = val
      console.log(val)
    },
    getUserGroupList() {
      userApi.userGroupList({ limit: 100 }).then(res => {
        this.groupList = res.data
      })
    },
    open() {
      this.getUserGroupList()
      this.dialogAdmin = true
      this.adminForm = {
        username: '',
        password: '',
        avatar: '',
        user_group: '',
        sex: 0,
        nickname: '',
        mobile: '',
        email: '',
        birthday: '',
        id: ''
      }
    },
    editUser(row) {
      this.getUserGroupList()
      this.dialogAdmin = true
      this.adminForm = { ...row }
      if (row.avatar) {
        this.iconUrl = row.avatar
      }
    },
    editUserStatus(row, status) {
      if (status == 3) {
        let check = true
        this.$confirm(
          '此操作将永久限制此会员的所有操作，所绑定的手机号和邮箱也不能重新注册！ 是否继续?',
          '禁用用户',
          {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
          }
        )
          .then(() => {
            userApi.userEditStatus({ id: row.id, status: status }).then(res => {
              if (res.code == 0) {
                this.$message.success(res.msg)
                this.getList()
              }
            })
          })
          .catch(() => {
            check = false
          })
      } else {
        userApi.userEditStatus({ id: row.id, status: status }).then(res => {
          if (res.code == 0) {
            this.$message.success(res.msg)
            this.getList()
          }
        })
      }
    },
    // 获取列表
    getList(type) {
      this.$refs.baseTable.getList(type)
      // this.val.page = this.page.currentPage
      // this.val.limit = this.page.size
      // this.val.account = this.searchForm.account
      // userApi.userList(this.val).then(res => {
      //   console.log(res.data, '---->')
      //   this.tableData = res.data
      //   this.page.total = res.count
      // })
    },

    // 提交
    submit() {
      this.$refs.adminForm.validate(valid => {
        if (valid) {
          if (!this.adminForm.id) {
            userApi
              .userAdd({
                ...this.adminForm
              })
              .then(res => {
                if (res.code === 0) {
                  this.$message.success(res.msg)
                  this.dialogAdmin = false
                  this.getList()
                }
              })
          } else {
            userApi.userEdit({ ...this.adminForm }).then(res => {
              if (res.code === 0) {
                this.$message.success(res.msg)
                this.dialogAdmin = false
                this.getList()
              }
            })
          }
        } else {
          this.$message.warning(this.$t('请填写必要信息'))
        }
      })
    },

    // 搜索
    search() {
      this.$refs.searchForm.validate(valid => {
        this.page.currentPage = 1
        this.getList()
      })
    },

    // 重置搜索框
    reset(searchForm) {
      this.searchForm = {
        account: ''
      }
    },
    // 分页规格改变
    handleSizeChange(val) {
      this.page.size = val
      this.page.currentPage = 1
      this.getList()
    },
    // 分页点击
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.user-form-container {
  ::v-deep .el-form-item__content {
    width: calc(100% - 80px);
    .el-select {
      width: calc(100%);
    }
  }
}
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
.el-table {
  margin-bottom: 20px;
}
</style>
